import 'dart:convert';
import 'package:http/http.dart' as http;

class IpLocationService {
  static const String _apiUrl = 'http://ip-api.com/json';
  
  /// 获取IP地理位置信息
  Future<IpLocationInfo?> getLocationInfo({String? ip}) async {
    try {
      final url = ip != null ? '$_apiUrl/$ip' : _apiUrl;
      final response = await http.get(
        Uri.parse(url),
        headers: {'Accept': 'application/json'},
      ).timeout(const Duration(seconds: 5));
      
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['status'] == 'success') {
          return IpLocationInfo.fromJson(data);
        }
      }
      return null;
    } catch (e) {
      print('Error getting IP location: $e');
      return null;
    }
  }
  
  /// 获取国旗emoji
  String getCountryFlag(String countryCode) {
    if (countryCode.isEmpty || countryCode.length != 2) {
      return '🌍';
    }
    
    // 将国家代码转换为国旗emoji
    final codePoints = countryCode.toUpperCase().codeUnits;
    final flag = String.fromCharCodes(
      codePoints.map((c) => 0x1F1E6 + c - 0x41),
    );
    return flag;
  }
}

class IpLocationInfo {
  final String country;
  final String countryCode;
  final String region;
  final String regionName;
  final String city;
  final String zip;
  final double lat;
  final double lon;
  final String timezone;
  final String isp;
  final String org;
  final String as;
  final String query;

  IpLocationInfo({
    required this.country,
    required this.countryCode,
    required this.region,
    required this.regionName,
    required this.city,
    required this.zip,
    required this.lat,
    required this.lon,
    required this.timezone,
    required this.isp,
    required this.org,
    required this.as,
    required this.query,
  });

  factory IpLocationInfo.fromJson(Map<String, dynamic> json) {
    return IpLocationInfo(
      country: json['country'] ?? '',
      countryCode: json['countryCode'] ?? '',
      region: json['region'] ?? '',
      regionName: json['regionName'] ?? '',
      city: json['city'] ?? '',
      zip: json['zip'] ?? '',
      lat: (json['lat'] ?? 0.0).toDouble(),
      lon: (json['lon'] ?? 0.0).toDouble(),
      timezone: json['timezone'] ?? '',
      isp: json['isp'] ?? '',
      org: json['org'] ?? '',
      as: json['as'] ?? '',
      query: json['query'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'country': country,
      'countryCode': countryCode,
      'region': region,
      'regionName': regionName,
      'city': city,
      'zip': zip,
      'lat': lat,
      'lon': lon,
      'timezone': timezone,
      'isp': isp,
      'org': org,
      'as': as,
      'query': query,
    };
  }

  /// 获取简短的位置描述
  String get shortLocation => city.isNotEmpty ? '$city, $country' : country;
  
  /// 获取完整的位置描述
  String get fullLocation {
    final parts = <String>[];
    if (city.isNotEmpty) parts.add(city);
    if (regionName.isNotEmpty) parts.add(regionName);
    if (country.isNotEmpty) parts.add(country);
    return parts.join(', ');
  }
}
